import React, { FC, useState, ChangeEvent, useEffect } from "react";
import classNames from "classnames/bind";
import style from "./index.module.scss";
import { Button, Typography, Flex, Input, Space, message } from "antd";
import { RollbackOutlined, SaveOutlined, EditOutlined } from "@ant-design/icons";
import { useNavigate, useParams } from "react-router-dom";
//引入工具栏
import EditorToolbar from "../EditorToolbar";
import useGetPageInfo_redux from "../../../hooks/useGetPageInfo_redux";
import { useDispatch } from "react-redux";
import { changePageInfoTtle } from "../../../store/pageInfoReducer";
import useGetComponentInfo_redux from "../../../hooks/useGetComponentInfo_redux";
//引入更新问卷api
import { updateQuestionData } from "../../../service";
//引入ahooks
import { useRequest, useDebounceFn, useKeyPress } from "ahooks";
const CBN = classNames.bind(style);
const { Title } = Typography;

const PageInfoTitle: FC = () => {
  const dispatch = useDispatch();
  const { title } = useGetPageInfo_redux();
  const [editState, seteditState] = useState(false);
  function handlechange(e: ChangeEvent<HTMLInputElement>) {
    const value = e.target.value;
    dispatch(changePageInfoTtle(value));
  }
  if (editState) {
    return (
      <Input
        value={title}
        onPressEnter={() => {
          seteditState(false);
        }}
        onBlur={() => {
          seteditState(false);
        }}
        onChange={handlechange}
      ></Input>
    );
  } else {
    return (
      <Space>
        <Title style={{ margin: "0", fontSize: "20px" }}>{title}</Title>
        <Button icon={<EditOutlined />} type="text" onClick={() => seteditState(true)}></Button>
      </Space>
    );
  }
};

//保存按钮
const SaveButton: FC = () => {
  //获取问卷的id
  const { id } = useParams();
  //获取组件列表
  const { componentList } = useGetComponentInfo_redux();
  //获取页面信息
  const pageInfo = useGetPageInfo_redux();

  const { run: savePage, loading } = useRequest(
    async () => {
      if (!id) return;
      await updateQuestionData(id, { componentList, pageInfo });
    },
    {
      manual: true,
    },
  );
  //监听快捷键
  useKeyPress(["ctrl.s", "meta.s"], (e: KeyboardEvent) => {
    e.preventDefault();
    if (!loading) {
      savePage();
    }
  });

  const { run: savePagedebounce } = useDebounceFn(
    () => {
      savePage();
    },
    {
      wait: 500,
    },
  );

  useEffect(() => {
    savePagedebounce();
  }, [pageInfo, componentList]);

  return (
    <Button icon={<SaveOutlined />} onClick={savePage} disabled={loading} loading={loading}>
      保存
    </Button>
  );
};

//发布按钮
const PublishButton: FC = () => {
  //获取问卷的id
  const { id } = useParams();
  //使用路由
  const nav = useNavigate();
  const { run: publishPage, loading } = useRequest(
    async () => {
      if (!id) return;
      await updateQuestionData(id, { ispublish: true });
    },
    {
      manual: true,
      onSuccess() {
        nav(`/question/stat/${id}`);
        message.success("发布成功");
      },
    },
  );

  return (
    <Button type="primary" onClick={publishPage} disabled={loading} loading={loading}>
      发布
    </Button>
  );
};

const EditorHead: FC = () => {
  const nav = useNavigate();
  return (
    <div className={CBN("header")}>
      <div className={CBN("left")}>
        <Flex align="center" gap="small">
          <Button
            icon={<RollbackOutlined />}
            type="link"
            onClick={() => {
              nav(-1);
            }}
          >
            返回
          </Button>
          <PageInfoTitle></PageInfoTitle>
        </Flex>
      </div>
      <div className={CBN("middle")}>
        <EditorToolbar></EditorToolbar>
      </div>
      <div className={CBN("right")}>
        <Flex gap="small" align="center">
          <SaveButton></SaveButton>
          <PublishButton></PublishButton>
        </Flex>
      </div>
    </div>
  );
};

export default EditorHead;
